package utils.backstage;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库操作工具类
 */
public class JDBCUtils {

    private static DataSource ds;

    /**
     * ds的getter方法
     * @return
     */
    public static DataSource getDs() {
        return ds;
    }

    /**
     * 初始化DataSource
     */
    static {
        Properties prop = new Properties();
        try {
            prop.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null;

        try {
            conn =  ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }


    /**
     * 关闭连接，释放资源
     * @param res
     * @param statement
     * @param conn
     */
    public static  void release(ResultSet res, Statement statement, Connection conn){

        try {
            if(res!=null)
                res.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (statement!=null)
                statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }




}
